﻿using BlogEngine.Gallery.Models;
using System.Collections.Generic;
using System.IO;
using System.Web;

namespace BlogEngine.Gallery.Data
{
    public class Repository
    {
        static string _dataFolder = HttpContext.Current.Server.MapPath("~/Packages/Extra");
        static string _uploadFolder = HttpContext.Current.Server.MapPath("~/Packages/Uploads");

        public static IEnumerable<string> GetUploaded()
        {
            var pkgs = new List<string>();

            if (!Directory.Exists(_uploadFolder))
                Directory.CreateDirectory(_uploadFolder);

            var pkgDir = new DirectoryInfo(_uploadFolder);

            foreach (var d in pkgDir.GetDirectories())
            {
                if (!File.Exists(Path.Combine(d.FullName, "note.txt")))
                {
                    var t = d.CreationTimeUtc;
                    pkgs.Add(d.Name + " (uploaded " + t.ToLongDateString() + ", " + t.ToShortTimeString() + ")");
                }
            }

            if (pkgs.Count == 0) pkgs.Add("Empty");

            return pkgs;
        }

        public static IEnumerable<string> GetRejected()
        {
            var pkgs = new List<string>();

            if (!Directory.Exists(_uploadFolder))
                Directory.CreateDirectory(_uploadFolder);

            var pkgDir = new DirectoryInfo(_uploadFolder);

            foreach (var d in pkgDir.GetDirectories())
            {
                string path = Path.Combine(d.FullName, "note.txt");

                if (File.Exists(path))
                {
                    var locker = new object();
                    lock (locker)
                    {
                        string text = "<b>" + d.Name + "</b>: ";
                        using (StreamReader streamReader = new StreamReader(path, System.Text.Encoding.UTF8))
                        {
                            pkgs.Add(text + streamReader.ReadToEnd());
                        }
                    }
                }
            }

            if (pkgs.Count == 0) pkgs.Add("Empty");
            return pkgs;
        }

        public static void UpdateCount(string id)
        {
            var fileName = string.Format(@"{0}\{1}.xml", _dataFolder, id);
            var pkg = new PackageExtra();

            if (File.Exists(fileName))
            {
                var locker = new object();
                lock (locker)
                {
                    var reader = new System.Xml.Serialization.XmlSerializer(typeof(PackageExtra));
                    var file = new System.IO.StreamReader(fileName);
                    pkg = (PackageExtra)reader.Deserialize(file);
                    pkg.DownloadCount++;
                    file.Close();
                }
            }
            else
            {
                pkg.Id = id;
                pkg.DownloadCount = 0; // OldCount(id);
            }
            SerializePkgExtra(pkg);
        }

        public static IEnumerable<PackageExtra> GetPackages()
        {
            var pkgs = new List<PackageExtra>();

            if (!Directory.Exists(_dataFolder))
                Directory.CreateDirectory(_dataFolder);

            var pkgDir = new DirectoryInfo(_dataFolder);

            foreach (var f in pkgDir.GetFiles())
            {
                if (f.Name.EndsWith(".xml"))
                {
                    var pkgId = f.Name.Replace(".xml", "");
                    var pkg = GetPackage(pkgId);
                    pkgs.Add(pkg);
                }
            }

            return pkgs;
        }

        public static PackageExtra GetPackage(string id)
        {
            var fileName = string.Format(@"{0}\{1}.xml", _dataFolder, id);
            var pkg = new PackageExtra();

            if (File.Exists(fileName))
            {
                var locker = new object();
                lock (locker)
                {
                    var reader = new System.Xml.Serialization.XmlSerializer(typeof(PackageExtra));
                    var file = new System.IO.StreamReader(fileName);
                    pkg = (PackageExtra)reader.Deserialize(file);
                    file.Close();
                }
            }
            else
            {
                pkg.Id = id;
                pkg.DownloadCount = 0;
                SavePackage(pkg);
            }
            return pkg;
        }

        public static void ResetCounts()
        {
            string pkgFolder = HttpContext.Current.Server.MapPath("~/Packages");
            var pkgDir = new DirectoryInfo(pkgFolder);

            foreach (var f in pkgDir.GetFiles())
            {
                if (f.Name.EndsWith(".nupkg"))
                {
                    var id = f.Name.Replace(".nupkg", "");
                    var fileName = string.Format(@"{0}\{1}.xml", _dataFolder, id);

                    var pkg = new PackageExtra();
                    pkg.Id = id;

                    pkg.DownloadCount = OldCount(id);

                    SerializePkgExtra(pkg);
                }
            }
        }

        public static void SavePackage(PackageExtra pkg)
        {
            SerializePkgExtra(pkg);
        }

        public static void SaveUploaded(PackageExtra pkg)
        {
            SerializePkgExtra(pkg, true);
        }

        #region Private methods

        static void SerializePkgExtra(PackageExtra pkg, bool pre = false)
        {
            var fileName = string.Format(@"{0}\{1}.xml", _dataFolder, pkg.Id);

            if (pre)
                fileName = string.Format(@"{0}\{1}\{1}.xml", _uploadFolder, pkg.Id);

            var locker = new object();

            lock (locker)
            {
                var writer = new System.Xml.Serialization.XmlSerializer(typeof(PackageExtra));
                var file = new System.IO.StreamWriter(fileName);

                writer.Serialize(file, pkg);
                file.Close();
            }
        }

        // transfer counts from old repository
        // if exists
        static int OldCount(string id)
        {
            id = id.ToLower().Substring(0, id.IndexOf("."));

            if (id == "addthis") return 4451;
            if (id == "adsensecontrol") return 795;
            if (id == "adsensewidget") return 1488;
            if (id == "alexasitestats") return 190;
            if (id == "alexatrafficgraph") return 176;
            if (id == "alltuts") return 8971;
            if (id == "alltuts_green") return 1749;
            if (id == "angel") return 924;
            if (id == "aquaria") return 906;
            if (id == "archie") return 1288;
            if (id == "arthemiapro") return 6308;
            if (id == "arthemiatwilight") return 3119;
            if (id == "badwordblocker") return 373;
            if (id == "barricade") return 1172;
            if (id == "betterwordcount") return 348;
            if (id == "biblescholar") return 866;
            if (id == "blacknight") return 2219;
            if (id == "blacknight-no-menu") return 988;
            if (id == "blackskyline") return 1543;
            if (id == "blackskyline-no-menu") return 754;
            if (id == "blogengine.googleplusone") return 500;
            if (id == "blogenginepaypaladdtobasketbutton") return 419;
            if (id == "blogenginepaypalbuynowbutton") return 484;
            if (id == "blogenginepaypaldonatebutton") return 731;
            if (id == "blogengineprotector") return 626;
            if (id == "blogstatistic") return 871;
            if (id == "bluehorizon") return 1458;
            if (id == "bluehorizon-no-menu") return 1943;
            if (id == "blueline") return 3469;
            if (id == "bluepigment") return 872;
            if (id == "blueskyline") return 1991;
            if (id == "boldy") return 13916;
            if (id == "brightside") return 1180;
            if (id == "businesstime") return 1467;
            if (id == "channelpro") return 5589;
            if (id == "coffee_live") return 349;
            if (id == "coffeehouse") return 1515;
            if (id == "commentsexport") return 437;
            if (id == "connect_with_me") return 274;
            if (id == "convertstyletocss") return 48;
            if (id == "coolblue") return 4593;
            if (id == "coolwater") return 1456;
            if (id == "darkblog") return 2834;
            if (id == "delicious") return 189;
            if (id == "desk-mess") return 1773;
            if (id == "detaileddownloadcounter") return 599;
            if (id == "devtyr_mobile") return 1312;
            if (id == "diesel") return 1467;
            if (id == "diggdigg") return 530;
            if (id == "dilectio") return 1496;
            if (id == "discovery") return 1069;
            if (id == "disquscommentssummary") return 701;
            if (id == "diva") return 1491;
            if (id == "elegantblog") return 5397;
            if (id == "elegantblue") return 2693;
            if (id == "envision") return 793;
            if (id == "evilcorporate") return 1052;
            if (id == "excerptimagesextension") return 718;
            if (id == "facebook") return 3076;
            if (id == "facebookcompartilhar") return 290;
            if (id == "facebooklike") return 3488;
            if (id == "facebookpopout") return 1211;
            if (id == "fastsearch") return 649;
            if (id == "fbpagelikebox") return 3261;
            if (id == "featuredpostslist") return 2412;
            if (id == "featuredpostsrotatorrevisited") return 541;
            if (id == "feedburner_email_sus") return 120;
            if (id == "feedjit") return 724;
            if (id == "feedsignature") return 394;
            if (id == "filesystemmanager") return 755;
            if (id == "flatblog") return 5087;
            if (id == "flattr") return 761;
            if (id == "flickrbar") return 1444;
            if (id == "freshcitrus") return 3882;
            if (id == "germaniumify") return 343;
            if (id == "googleasyncanalytics") return 3127;
            if (id == "googlebuzz") return 502;
            if (id == "googleplusone") return 968;
            if (id == "grayandgold") return 1253;
            if (id == "grayandgold-no-menu") return 1384;
            if (id == "greenline-no-menu") return 986;
            if (id == "healthy") return 813;
            if (id == "heartbeat") return 1197;
            if (id == "heyos_control") return 233;
            if (id == "i3theme") return 1359;
            if (id == "illacrimo") return 1933;
            if (id == "imageguard") return 1047;
            if (id == "imagezoomextension") return 1594;
            if (id == "imprezz9") return 1145;
            if (id == "instagram-widget") return 1107;
            if (id == "interlude") return 2873;
            if (id == "jacobs_ladder") return 884;
            if (id == "jcarousel") return 1134;
            if (id == "jq-mobile") return 3620;
            if (id == "justblog") return 1523;
            if (id == "kickback") return 1148;
            if (id == "liquidnautica") return 1169;
            if (id == "liveviewscount") return 862;
            if (id == "markdowndeepformatter") return 38;
            if (id == "markdownformatter") return 363;
            if (id == "me_live") return 331;
            if (id == "metrodark") return 2993;
            if (id == "metrolight") return 9667;
            if (id == "miniblog") return 548;
            if (id == "mobilemetro") return 5559;
            if (id == "modern") return 1731;
            if (id == "moffeynow") return 760;
            if (id == "monthlyblogposts") return 420;
            if (id == "mostread") return 1523;
            if (id == "movetotop") return 1341;
            if (id == "mp3player") return 3415;
            if (id == "n3oeco") return 802;
            if (id == "newsletter") return 1050;
            if (id == "nirudefault") return 320;
            if (id == "nivoslider") return 3609;
            if (id == "notepad-chaos") return 1790;
            if (id == "notmetro") return 1183;
            if (id == "oldschool") return 798;
            if (id == "paperclip-cactus") return 1023;
            if (id == "passwordprotect") return 800;
            if (id == "picasa") return 1230;
            if (id == "picasa-widget") return 853;
            if (id == "pinnedmode") return 610;
            if (id == "plusonepro") return 1531;
            if (id == "pollwidget") return 2342;
            if (id == "popularposts") return 1378;
            if (id == "postview") return 1935;
            if (id == "predilection") return 659;
            if (id == "prettyphoto2") return 2904;
            if (id == "problue") return 1006;
            if (id == "professionallight") return 900;
            if (id == "quotations") return 488;
            if (id == "reading") return 302;
            if (id == "recenttweets") return 2896;
            if (id == "redfever") return 811;
            if (id == "redskyline") return 758;
            if (id == "redtuts") return 487;
            if (id == "royalblue") return 726;
            if (id == "scribdviewer") return 275;
            if (id == "scriptinjection") return 605;
            if (id == "showcase") return 962;
            if (id == "simple-life") return 964;
            if (id == "simpleblog") return 2407;
            if (id == "simpleblog29") return 1912;
            if (id == "simpledownloadcounter") return 301;
            if (id == "simplicity") return 1322;
            if (id == "singularity") return 1169;
            if (id == "sizzle") return 992;
            if (id == "smushy") return 392;
            if (id == "socialbarextension") return 1676;
            if (id == "socialbuzz") return 1445;
            if (id == "socialcards") return 3223;
            if (id == "socialpublish") return 1535;
            if (id == "standardprotheme") return 1506;
            if (id == "stardust") return 1031;
            if (id == "statistics") return 769;
            if (id == "tagcanvas") return 577;
            if (id == "tnycowidget") return 503;
            if (id == "tomatoes") return 1071;
            if (id == "topposts") return 882;
            if (id == "torrentsearch") return 156;
            if (id == "tweetme") return 1303;
            if (id == "tweets") return 86;
            if (id == "twitterpopout") return 614;
            if (id == "twitterwidgets") return 673;
            if (id == "unknown") return 1003;
            if (id == "vimeoplayer") return 584;
            if (id == "vimeoviewer") return 453;
            if (id == "vs-achievements") return 657;
            if (id == "websiteha") return 1756;
            if (id == "wikipedialink") return 452;
            if (id == "windowslivetheme") return 991;
            if (id == "wordcount") return 739;
            if (id == "xtremeblogg") return 951;
            if (id == "yoko") return 3676;
            if (id == "youtube") return 1929;
            if (id == "youtubeplayer") return 1870;
            if (id == "youtubeviewer") return 1020;

            return 0;
        }

        #endregion
    }
}